package org.eenie.kdassistant.net.zzt_api;

import com.alibaba.fastjson.JSON;

import org.eenie.kdassistant.net.AssistantApi;
import org.eenie.kdassistant.net.ParamsAnalog;
import org.eenie.kdassistant.net.common.CommonApi;
import org.eenie.kdassistant.utils.zzt_encode.DataDigestUtil;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

/**
 * Created by Eenie on 2017/8/11.
 * Email: eeniework@gmail.com
 * Des:
 */

public class ZZTApi implements CommonApi {
    private ZZTService mZZTService;
    private final int DEFUALT_TIME = 10;

    private AssistantApi mAssistantApi;


    private SimpleDateFormat mSimpleDateFormat;

    private ParamsAnalog mParamsAnalog;


    public ZZTApi(ParamsAnalog paramsAnalog, AssistantApi assistantApi) {

        mParamsAnalog = paramsAnalog;
        mAssistantApi = assistantApi;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(DEFUALT_TIME, TimeUnit.SECONDS)
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();

        mZZTService = new Retrofit.Builder()
                .baseUrl("https://zztgateway.zto.com")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(ZZTService.class);


        mSimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }


    @Override
    public Observable<ResponseBody> addAcceptExpress(String express) {


//        String data = "{\"scanData\":[{\"pdaScanData\":{\"billCode\":\"762197878520\",\"date\":\"20170814125157\",\"empCode\":\"02179.008\",\"fenjianCode\":\"\",\"\":\"04\"},\"index\":0}]}";

        Map<String, Object> params = new HashMap<>();

        List expressList = new ArrayList();

        Map<String, Object> data = new HashMap<>();
        Map<String, Object> scanData = new HashMap<>();

        scanData.put("billCode", express);
        scanData.put("date", mSimpleDateFormat.format(System.currentTimeMillis()));
        scanData.put("empCode", mParamsAnalog.getZzt_empCode());
        scanData.put("fenjianCode", "");
        scanData.put("type", "04");

        data.put("index", 0);
        data.put("pdaScanData", scanData);


        expressList.add(data);
        params.put("scanData", expressList);

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("msg_type", "SCAN_UPLOAD");
        builder.add("data", JSON.toJSONString(params));
        builder.add("company_id", "APP_ANDROID");
        builder.add("data_digest", DataDigestUtil.digest(JSON.toJSONString(params), mParamsAnalog.getZzt_token(), "UTF-8"));
        builder.add("open_id", mParamsAnalog.getKdy_sessionId());
        builder.add("version", "4.1.0");
        builder.add("timestamp", String.valueOf(System.currentTimeMillis()));
        return mZZTService.ReqData(mParamsAnalog.getZzt_token(), mParamsAnalog.getZzt_opendid(), builder.build());
    }



    public Observable<ResponseBody> login() {

        FormBody.Builder builder = new FormBody.Builder();

        builder.add("msg_type", "INFO_USER");
        builder.add("data", "[]");
        builder.add("company_id", "APP_ANDROID");
        builder.add("data_digest", DataDigestUtil.digest(JSON.toJSONString("[]"), mParamsAnalog.getZzt_token(), "UTF-8"));
        builder.add("open_id", mParamsAnalog.getZzt_opendid());
        builder.add("version", "4.1.0");
        builder.add("timestamp", String.valueOf(System.currentTimeMillis()));


        return mZZTService.ReqData(mParamsAnalog.getZzt_token(), mParamsAnalog.getZzt_opendid(), builder.build());
    }




    @Override
    public Observable<ResponseBody> fetchCom(String express) {
        return mAssistantApi.fetchCom(express);
    }


    @Override
    public Observable<ResponseBody> addSignExpress(String express) {

//        {"scanData":[{"pdaScanData":{"billCode":"453123204617","date":"20170915172521","empCode":"02104.089","latitude":"31.208269","longitude":"121.478685","signType":"本人","type":"05"},"index":0}]}
        Map<String, Object> params = new HashMap<>();
        List expressList = new ArrayList();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> scanData = new HashMap<>();
        scanData.put("billCode", express);
        scanData.put("date", mSimpleDateFormat.format(System.currentTimeMillis()));
        scanData.put("empCode", mParamsAnalog.getZzt_empCode());
        scanData.put("latitude", mParamsAnalog.getDevice_lat());
        scanData.put("longitude", mParamsAnalog.getDevice_lng());
        scanData.put("signType", "本人");
        scanData.put("type", "05");
        data.put("index", 0);
        data.put("pdaScanData", scanData);
        expressList.add(data);
        params.put("scanData", expressList);


        FormBody.Builder builder = new FormBody.Builder();
        builder.add("msg_type", "SCAN_UPLOAD");
        builder.add("data", JSON.toJSONString(params));
        builder.add("company_id", "APP_ANDROID");
        builder.add("data_digest", DataDigestUtil.digest(JSON.toJSONString(params), mParamsAnalog.getZzt_token(), "UTF-8"));
        builder.add("open_id", mParamsAnalog.getKdy_sessionId());
        builder.add("version", "4.1.0");
        builder.add("timestamp", String.valueOf(System.currentTimeMillis()));
        return mZZTService.ReqData(mParamsAnalog.getZzt_token(), mParamsAnalog.getZzt_opendid(), builder.build());

    }
}
